[Python]@property的使用

Why @property?

如果对于一个类,我们希望用getter和setter来控制成员变量的赋值和取值,又不希望对于每一个成员变量都显式的写出getter和setter, 就可以用@property

1
2
3
4
5
6
7
8
9
10
11
12
class Student:

# this is the getter
@property
def score(self):
return self._score

# this is the setter
@score.setter
def score(self, value):
# value check here
self._score = value

When calling

1
2
Student().score # get_score
# instead of Student()._score directly

More details about the func property here

Reference